<?php
namespace app\common\service;

use app\common\helper\ExcelHelper;
use app\common\util\Util;
use think\Model;

class StudentInformationService extends BaseService
{
    /**
     * 获取 学员资料列表
     * @param $sid
     * @param $search
     * @param $p
     * @param $pageSize
     * @return mixed
     */
    public function GetStudentList($sid,$search='',$status='',$p=1,$pageSize=10){
        //获取学员/顾客基本列表信息
        $where = [
            's.sid' => $sid,
            's.formal_status' => 1
        ];
        if(!empty($search)){
            $where['s.phone|u.user_nickname|s.name'] = ['like','%'.$search.'%'];
        }
        if($status == 1){
            $where['s.uid'] = ['>',0];
        }
        if($status == 2){
            $where['s.uid'] = ['=',0];
        }
        $list_count = db()->name('students')
            ->alias('s')
            ->join('user_integral ui','s.sid = ui.sid and s.uid = ui.userid','left')
            ->join('user u','s.uid = u.user_id','left')
            ->where($where)
            ->count();
        $field = 's.*,u.user_nickname,u.user_headimgurl';
        $list = db()->name('students')
            ->alias('s')
            ->join('user_integral ui','s.sid = ui.sid and s.uid = ui.userid','left')
            ->join('user u','s.uid = u.user_id','left')
            ->where($where)
            ->field($field)
            ->limit(($p-1) * $pageSize , $pageSize)
            ->select();

        if($list){
            $tagServer = new TagService();
            $studentServer = new StudentService();
            foreach($list as $k => $v){
                //公司
//                $list[$k]['company'] = unserialize($v['company']);
//                $temp = preg_replace_callback('#s:(\d+):"(.*?)";#s',function($match){return 's:'.strlen($match[2]).':"'.$match[2].'";';}, $v['company']);
//                $list[$k]['company'] = unserialize($temp);
                $list[$k]['company'] = Util::unserializeStr($v['company']);
                $list[$k]['phone_hide'] = Util::hidestr($v['phone'],3,4);

                if($v['uid'] > 0){
                    //兴趣爱好
                    $list[$k]['tag'] = $tagServer->getUserTagList($sid,$v['uid'],2);
//                    $list[$k]['class'] = $studentServer->getStudentClass($sid,$v['uid']);
                }else{
                    $list[$k]['tag'] = [];
//                    $list[$k]['class'] = db('classes')->where(['classid' => $v['classid']])->value('name');
                }
//                $list[$k]['class'] = db('classes')->where(['classid' => $v['classid']])->value('name');
                $class = db('class_students cs')
                            ->join('classes c', 'cs.classid = c.classid', 'LEFT')
                            ->field('c.name')
                            ->where(['cs.sid' => $sid, 'cs.studentsid' => $v['id']])
                            ->select();
                $class_name = [];
                if($class){
                    foreach($class as $val){
                        $class_name[] = $val['name'];
                    }
                }
                $list[$k]['class'] = $class_name ? implode('、',$class_name) : '暂无';

            }
        }
        return ['content' => $list,'page' =>['count' =>$list_count]];
    }

    /**
     * 获取学员详情
     * @param $sid
     * @param $id
     * @return array
     */
    public function GetStudentDetail($sid,$id){
        $where = [
            'sid' => $sid,
            'id' => $id,
            'formal_status' => 1
        ];
        $info = db('students')->where($where)->find();
        if(empty($info)){
            return ['status' => 0,'msg' => '参数错误'];
        }else{
            $data['content'] = $info;
            return ['status' => 1,'data' => $data];
        }
    }

    /**
     * 编辑学员资料
     * @param $sid
     * @param $id
     * @param $postParam
     * @return int|string
     * @throws \think\Exception
     */
    public function EditStudent($sid,$id,$postParam){
        $where = [
            'id' => $id,
            'sid' => $sid
        ];
        $update = [
            'name' => $postParam['name'],
            'phone' => $postParam['phone'],
            'birthday' => $postParam['birthday'] ?? '',
            'cardid' => $postParam['cardid'] ?? '',
        ];
        $res = db('students')->where($where)->update($update);
        return $res;
    }

    /**
     * 上传学员资料
     * @param $sid
     * @param $classid
     * @return array
     * @throws \think\Exception
     */
    public function ImportStudent($sid,$classid){

        if (!empty($_FILES)) {
            $time = date('Y-m-d',time());
            $file_path = './uploads/students/'.$sid.'/'.$time.'/';

            if(!is_dir($file_path)){
                mkdir($file_path,0777,true);
            }
            //获取文件的后缀名
            $name_after = explode('.',$_FILES['import_file']['name']);
            move_uploaded_file($_FILES['import_file']['tmp_name'],$file_path.time().'.'.$name_after[1]);
            //文件的路径
            $file_name = $file_path.time().'.'.$name_after[1];
            $sheetData = ExcelHelper::import($file_name);
            if(!empty($sheetData) && is_array($sheetData)){
                foreach($sheetData as $k => $v){
                    /*if($k == 0){
                        if ($v['0'] != '姓名') {
                            return ['status' => 0,'msg' => '格式不正确,A1需要设置为姓名'];
                        }
                        if ($v['1'] != '联系方式') {
                            return ['status' => 0,'msg' => '格式不正确,B1需要设置为联系方式'];
                        }
                        if ($v['2'] != '生日') {
                            return ['status' => 0,'msg' => '格式不正确,C1需要设置为生日'];
                        }
                        if ($v['3'] != '身份证号') {
                            return ['status' => 0,'msg' => '格式不正确,D1需要设置为身份证号'];
                        }
                        if ($v['4'] != '公司') {
                            return ['status' => 0,'msg' => '格式不正确,E1需要设置为公司'];
                        }
                        if ($v['5'] != '主营业务') {
                            return ['status' => 0,'msg' => '格式不正确,F1需要设置为主营业务'];
                        }
                        if ($v['6'] != '人生格言') {
                            return ['status' => 0,'msg' => '格式不正确,G1需要设置为人生格言'];
                        }
                        if ($v['7'] != '兴趣爱好') {
                            return ['status' => 0,'msg' => '格式不正确,H1需要设置为兴趣爱好'];
                        }
                        if ($v['8'] != '顾问姓名') {
                            return ['status' => 0,'msg' => '格式不正确,H1需要设置为顾问姓名'];
                        }
                        if ($v['9'] != '顾问电话') {
                            return ['status' => 0,'msg' => '格式不正确,H1需要设置为顾问电话'];
                        }
                    }*/

                    if($k == 0){
                        if (mb_strpos($v['0'], '姓名')) {
                            return ['status' => 0,'msg' => '格式不正确,A1需要设置为姓名'];
                        }
                        if (mb_strpos($v['1'], '联系方式')) {
                            return ['status' => 0,'msg' => '格式不正确,B1需要设置为联系方式'];
                        }
                        if (mb_strpos($v['2'], '生日')) {
                            return ['status' => 0,'msg' => '格式不正确,C1需要设置为生日'];
                        }
                        if (mb_strpos($v['3'], '身份证号')) {
                            return ['status' => 0,'msg' => '格式不正确,D1需要设置为身份证号'];
                        }
                        if (mb_strpos($v['4'], '公司')) {
                            return ['status' => 0,'msg' => '格式不正确,E1需要设置为公司'];
                        }
                        if (mb_strpos($v['5'], '主营业务')) {
                            return ['status' => 0,'msg' => '格式不正确,F1需要设置为主营业务'];
                        }
                        if (mb_strpos($v['6'], '人生格言')) {
                            return ['status' => 0,'msg' => '格式不正确,G1需要设置为人生格言'];
                        }
                        if (mb_strpos($v['7'], '兴趣爱好')) {
                            return ['status' => 0,'msg' => '格式不正确,H1需要设置为兴趣爱好'];
                        }
                        if (mb_strpos($v['8'], '顾问姓名')) {
                            return ['status' => 0,'msg' => '格式不正确,H1需要设置为顾问姓名'];
                        }
                        if (mb_strpos($v['9'], '顾问电话')) {
                            return ['status' => 0,'msg' => '格式不正确,H1需要设置为顾问电话'];
                        }
                    }
                    if($k > 0){

                        if(!$v['1'])
                        {
                            return ['status' => 0,'msg' => '格式不正确,学员的联系方式不能为空，请填写完成后再次导入'];
                        }


                        //$data = [];
                        $data = [
                            'uid' => 0,
                            'user_integral_id' => 0,
                            'sid'=>$sid,
                            'name' => $v['0'],
                            'phone' => $v['1'],
                            'phone_bind_status' => 1,
                            'birthday' => $v['2'],
                            'cardid' => $v['3'],
                            'business' => $v['5'],
                            'life_motto' => $v['6'],
                            'hobby' => $v['7'],
                            'classid' => $classid,
                            'addtime' => time(),
                            'status' => 1,
                            'formal_status' => $classid  ? 1 : 0,
                            'sign_addtime' => time()
                        ];
                        //顾问
                        $counsoler_phone = $v['9'];

                        $counselor_id = db('students')->where(['sid' => $sid,'phone' => $counsoler_phone])->value('uid');
                        if(empty($counselor_id)){
                            $counselor_id = db('user u')
                                            ->join('user_integral ui', 'u.user_id = ui.userid')
                                            ->where(['u.user_mobile' => $counsoler_phone, 'ui.sid' => $sid])
                                            ->value('u.user_id');
                        }
                        \think\Log::record('导入数据.counselor_id=>'.$counsoler_phone.'->'.$counselor_id);

                        $data['counselor_id'] = $counselor_id;

                        if(!empty($v['4'])){
                            $company_array=explode(';',$v['4']);
                            if(!empty($company_array)){

                                foreach($company_array as $k=>$vo){
                                    $arr=explode('/',$vo);
                                    $company[$k]['cname']=$arr[0] ?? '';
                                    $company[$k]['position']=$arr[1] ?? '';
                                    $company[$k]['address']=$arr[2] ?? '';

                                }
//                                $data['company'] = serialize($company);
                                $data['company'] = Util::serializeStr($company);
                            }
                        }

                        $user_id = 0;
                        $students = db('students')->where(['phone' => $data['phone'],'sid'=>$sid])->field(true)->find();
                        if ($students) {
                            $students_id = $students['id'];
                            $user_id = $students['uid'];
                            //更新user_integral表中的parent_id和counselor_id
                            if($user_id) {
                                db('user_integral')
                                    ->where(['userid' => $user_id, 'sid' => $sid])
                                    ->update(['parent_id' => $counselor_id, 'counselor_id' => $counselor_id, 'students_id' => $students_id]);

                                $data['uid'] = $user_id;
                            }
                            $user_re = db('students')->where(array('phone' => $data['phone'],'sid'=>$sid))->update($data);
                            if(!$user_re){
                                return ['status' => 0,'msg' => '导入出错'];
                            }

                            if($classid){
                                $this->setClassStudents($user_id,$classid,$sid,$students_id);
                            }

                            continue;
                        } else {
                            $id = db('students')->insertGetId($data);
                            $students_id = $id;
                            if (!$id) {
                                return ['status' => 0,'msg' => '导入出错'];
                            }
                            else
                            {
                                if($classid){
                                    $this->setClassStudents($user_id,$classid,$sid,$students_id);
                                }
                            }
                        }


                    }
                }
                return ['status' => 1];
            }else{
                return ['status' => 0,'msg' => '请添加资料'];
            }
        }

    }

    private function setClassStudents($user_id,$classid,$sid,$students_id)
    {

        // 用学员ID去查询班级学员表，没有记录才写入
        $class_students = db('class_students')->where(['studentsid' => $students_id, 'classid' => $classid, 'sid' => $sid])->field(true)->find();

        if (!$class_students) {
            $cs['uid'] = $user_id;
            $cs['classid'] = $classid;
            $cs['sid'] = $sid;
            $cs['studentsid'] = $students_id;
            $cs['addtime'] = time();
            db('class_students')->insertGetId($cs);
        }

        db('classes')->where(['sid' => $sid, 'classid' => $classid])->setInc('total_numbe', 1);

    }

}